package com.control;

import com.dbutil.UtilJdbc;
import com.entity.Push_work;
import com.entity.User;
import com.entity.User_role;
import com.entity.Works;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取密码账户类型
        String uname = request.getParameter("uname");
        String upassword = request.getParameter("upassword");
        String type = request.getParameter("type");

        //创建jdbc对象
        UtilJdbc utilJdbc = new UtilJdbc();
        //根据用户名和密码去查询用户
        User user = utilJdbc.login(uname,upassword);
        //获取对象id
        Integer id = user.getId();
        //根据对象id去查询用户角色表中的role_id
        User_role ur=utilJdbc.findUserrole(id);
        Integer role_id = ur.getRole_id();
        List<Push_work> list = utilJdbc.workList();
        //查询学生做的作业
        List<Works> list1=utilJdbc.doWork();
        if(user==null){
           // request.setAttribute("error", "用户名或密码错误");
            response.sendRedirect("index.jsp?error=yes");
        }else{
            //登陆成功
            //保存登陆信息
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setAttribute("list",list);
            session.setAttribute("list1",list1);
            if(type.equals("学生")&&role_id==2){
                request.getRequestDispatcher("/LoginPag/StudentAmong.jsp").forward(request, response);
            }else if(type.equals("教师")&&role_id==1){
                request.getRequestDispatcher("/LoginPag/TeacherAmong.jsp").forward(request, response);
            }else {
                response.sendRedirect("index.jsp?error=yes");
            }
        }
    }
}
